package org.chench.extra.logsift.websocket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * 文本消息处理提
 * @author chench
 * @date 2025.05.17
 */
public class WebSocketTextHandler extends TextWebSocketHandler {
    private static final Logger logger = LoggerFactory.getLogger(WebSocketTextHandler.class);

    /**
     * 客户端发送消息
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        logger.info("handleTextMessage session:{}, message payload:{}", session.getId(), message.getPayload());
        //session.sendMessage(new TextMessage("Hello, client: " + session.getId() + " msg: " + message.getPayload()));
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 连接建立之后
        logger.info("连接建立之后: {}", session.getUri().getQuery());
        // 装饰原始会话以支持并发
        WebSocketSession concurrentSession = WebSocketSessionHandler.createConcurrentSession(session);
        WebSocketSessionHandler.saveSession(concurrentSession);
        //WebSocketSessionHandler.sendMessageSafely("......");
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        // 连接关闭之后
        logger.info("连接关闭之后: {}", status.toString());
        super.afterConnectionClosed(session, status);
    }
}
